package statistics;

import java.util.Random;


public class GammaDistribution extends Distribution{

    protected double lambda;
    protected double alpha;
    
    public GammaDistribution( double alpha  , double lambda, Random random ){
        this.alpha = alpha;
        this.lambda = lambda;
    }
            

    public double expectation() {
       return alpha/lambda;
    }


    public double variance() {
        return alpha/(lambda*lambda);
    }


    public double nextRandom() {
        double k = Math.floor(alpha);
        double a = alpha -k;
        double y = 0;
        double x;
        double p;
        double u1;
        double u;
        double e = Math.exp(1);
        double product=1;
        
        if(a>0) {
            while(y==0) {
                u = random.nextDouble();
                p = u * (e+a)/e;
                if(p <=1) {
                    x = Math.pow(p, 1/a);
                    u1 = random.nextDouble();
                    if(u1 <= Math.exp(-x))
                        y = x;
                } else {
                    x = -Math.log(p/a);
                    u1 = random.nextDouble();
                    if (u1 <= Math.pow(x, a-1))
                        y = x;
                }
            }
        }
        for(int i=1; i<=k; i++){
            product = product*random.nextDouble();
        }
        return (y-Math.log(product))/lambda;
    }
    
    
}